import tushare as ts
import pandas as pd
import datetime

def time_to_group(time_str):
    return time_str[:3] + "0:00"


def tran_type(t):
    if t == "买盘":
        return 1
    if t == "卖盘":
        return -1
    else:
        return 0


def tran_row(v, t, small, big):
    if not big:
        if v >= small:
            return v * t
        else:
            return 0
    if small <= v < big:
        return v * t
    return 0


def sum_func(x):
    return pd.Series({
        'price': x['price'].iloc[-1],
        'vl': sum(x['vl']),
        'l': sum(x['l']),
        'm': sum(x['m']),
        's': sum(x['s'])
    })


def tick_to_moneyflow(df: pd.DataFrame):
    print(df.head())
    df["timeGroup"] = df.time.apply(lambda x: x[:4] + "0:00")
    df["type"] = df.type.apply(tran_type)
    df["vl"] = df.apply(lambda row: tran_row(row["amount"], row["type"], 500000, None), axis=1)
    df["l"] = df.apply(lambda row: tran_row(row["amount"], row["type"], 200000, 500000), axis=1)
    df["m"] = df.apply(lambda row: tran_row(row["amount"], row["type"], 100000, 200000), axis=1)
    df["s"] = df.apply(lambda row: tran_row(row["amount"], row["type"], 0, 100000), axis=1)
    return df.groupby(df['timeGroup']).apply(sum_func).reset_index()


# 分组聚合+拼接
def concat_func(x):
    return pd.Series({
        '爱好':','.join(x['爱好'].unique()),
        '性别':','.join(x['性别'].unique())
    })

# result=df.groupby(df['姓名']).apply(concat_func).reset_index()

# convert date column do datetime type



def is_in_range(x):
    if x['Date'] > '28-02-2010 00:00:00' and x['Date'] < '31-08-2014 00:00:00':
        return 1
    else:
        return 0


if __name__ == "__main__":
    # df: pd.DataFrame = ts.get_tick_data('601628', date='2018-12-12', src='tt')
    # df1 = tick_to_moneyflow(df)
    # print(df1)
    df: pd.DataFrame = ts.get_tick_data('601628', date='2020-01-23', src='tt')
    df1 = tick_to_moneyflow(df)

    histories_5m['300343.SZ']['day'] = histories_5m['300343.SZ']['date'].dt.date
    df.groupby(df['date'].map(is_in_range))
    print(df1)

    today = histories_5m['300343.SZ']['day'][0].strftime('%Y-%m-%d')
    print(histories_5m['300343.SZ'].tail())
    selector = ((histories_5m['300343.SZ'].index.hour == 14) & (histories_5m['300343.SZ'].index.minute == 55))
    print(histories_5m['300343.SZ'][selector])

    s_date = datetime.datetime.strptime('20050606', '%Y%m%d').date()
    e_date = datetime.datetime.strptime('20071016', '%Y%m%d').date()
    df = df[(df['tra_date'] >= s_date) & (df['tra_date'] <= e_date)]

    # pandas.DataFrame.resample根据时间聚合采样（一）
    #https://pandas.pydata.org/docs/user_guide/timeseries.html#timeseries-offset-aliases；
    # vol['week'] = vol.index.week
    # vol['year'] = vol.index.year
    # vol.head()